/**
 * 统一错误类型定义
 * 建立标准化的错误分类和错误码体系
 */

/**
 * 错误级别枚举
 */
export enum ErrorLevel {
    /** 致命错误 - 导致系统无法正常运行 */
    FATAL = 'FATAL',
    /** 错误 - 功能执行失败但不影响系统运行 */
    ERROR = 'ERROR',
    /** 警告 - 潜在问题或不推荐的操作 */
    WARN = 'WARN',
    /** 信息 - 一般信息记录 */
    INFO = 'INFO',
    /** 调试 - 调试信息 */
    DEBUG = 'DEBUG'
}

/**
 * 错误分类枚举
 */
export enum ErrorCategory {
    /** 系统错误 */
    SYSTEM = 'SYSTEM',
    /** 业务逻辑错误 */
    BUSINESS = 'BUSINESS',
    /** 验证错误 */
    VALIDATION = 'VALIDATION',
    /** 权限错误 */
    AUTHORIZATION = 'AUTHORIZATION',
    /** 网络错误 */
    NETWORK = 'NETWORK',
    /** 数据库错误 */
    DATABASE = 'DATABASE',
    /** 配置错误 */
    CONFIG = 'CONFIG',
    /** 第三方服务错误 */
    EXTERNAL = 'EXTERNAL'
}

/**
 * 标准错误码定义
 * 格式：{分类}_{具体错误}_{序号}
 */
export const ERROR_CODES = {
    // 系统错误 (SYSTEM_*)
    SYSTEM_INITIALIZATION_FAILED: 'SYSTEM_001',
    SYSTEM_SERVICE_UNAVAILABLE: 'SYSTEM_002',
    SYSTEM_MEMORY_OVERFLOW: 'SYSTEM_003',
    SYSTEM_TIMEOUT: 'SYSTEM_004',
    SYSTEM_DEPENDENCY_MISSING: 'SYSTEM_005',
    
    // 业务逻辑错误 (BUSINESS_*)
    BUSINESS_ITEM_NOT_FOUND: 'BUSINESS_001',
    BUSINESS_INSUFFICIENT_BALANCE: 'BUSINESS_002',
    BUSINESS_OPERATION_NOT_ALLOWED: 'BUSINESS_003',
    BUSINESS_DUPLICATE_OPERATION: 'BUSINESS_004',
    BUSINESS_RESOURCE_EXHAUSTED: 'BUSINESS_005',
    BUSINESS_STATE_INVALID: 'BUSINESS_006',
    
    // 验证错误 (VALIDATION_*)
    VALIDATION_PARAMETER_MISSING: 'VALIDATION_001',
    VALIDATION_PARAMETER_INVALID: 'VALIDATION_002',
    VALIDATION_FORMAT_ERROR: 'VALIDATION_003',
    VALIDATION_RANGE_ERROR: 'VALIDATION_004',
    VALIDATION_TYPE_ERROR: 'VALIDATION_005',
    
    // 权限错误 (AUTH_*)
    AUTH_USER_NOT_FOUND: 'AUTH_001',
    AUTH_PERMISSION_DENIED: 'AUTH_002',
    AUTH_TOKEN_INVALID: 'AUTH_003',
    AUTH_SESSION_EXPIRED: 'AUTH_004',
    AUTH_RATE_LIMITED: 'AUTH_005',
    
    // 网络错误 (NETWORK_*)
    NETWORK_CONNECTION_FAILED: 'NETWORK_001',
    NETWORK_REQUEST_TIMEOUT: 'NETWORK_002',
    NETWORK_SERVICE_UNAVAILABLE: 'NETWORK_003',
    
    // 数据库错误 (DATABASE_*)
    DATABASE_CONNECTION_FAILED: 'DATABASE_001',
    DATABASE_QUERY_FAILED: 'DATABASE_002',
    DATABASE_TRANSACTION_FAILED: 'DATABASE_003',
    DATABASE_CONSTRAINT_VIOLATION: 'DATABASE_004',
    DATABASE_RECORD_NOT_FOUND: 'DATABASE_005',
    
    // 配置错误 (CONFIG_*)
    CONFIG_FILE_NOT_FOUND: 'CONFIG_001',
    CONFIG_PARSE_ERROR: 'CONFIG_002',
    CONFIG_VALIDATION_FAILED: 'CONFIG_003',
    CONFIG_VALUE_INVALID: 'CONFIG_004',
    
    // 外部服务错误 (EXTERNAL_*)
    EXTERNAL_API_ERROR: 'EXTERNAL_001',
    EXTERNAL_SERVICE_TIMEOUT: 'EXTERNAL_002',
    EXTERNAL_RATE_LIMITED: 'EXTERNAL_003'
} as const;

/**
 * 错误码类型
 */
export type ErrorCode = typeof ERROR_CODES[keyof typeof ERROR_CODES];

/**
 * 错误上下文信息
 */
export interface ErrorContext {
    /** 用户ID */
    userId?: string;
    /** 请求ID */
    requestId?: string;
    /** 服务名称 */
    serviceName?: string;
    /** 方法名称 */
    methodName?: string;
    /** 附加数据 */
    metadata?: Record<string, any>;
    /** 堆栈跟踪 */
    stackTrace?: string;
    /** 时间戳 */
    timestamp?: number;
}

/**
 * 错误详情接口
 */
export interface ErrorDetails {
    /** 错误码 */
    code: ErrorCode;
    /** 错误消息 */
    message: string;
    /** 错误级别 */
    level: ErrorLevel;
    /** 错误分类 */
    category: ErrorCategory;
    /** 错误上下文 */
    context?: ErrorContext;
    /** 内部错误 */
    innerError?: Error;
    /** 用户友好的错误消息 */
    userMessage?: string;
    /** 解决建议 */
    suggestion?: string;
}

/**
 * 标准化的游戏错误类
 */
export class GameError extends Error {
    public readonly code: ErrorCode;
    public readonly level: ErrorLevel;
    public readonly category: ErrorCategory;
    public readonly context: ErrorContext;
    public readonly innerError?: Error;
    public readonly userMessage: string;
    public readonly suggestion?: string;
    public readonly timestamp: number;

    constructor(details: ErrorDetails) {
        super(details.message);
        
        this.name = 'GameError';
        this.code = details.code;
        this.level = details.level;
        this.category = details.category;
        this.context = {
            timestamp: Date.now(),
            ...details.context
        };
        this.innerError = details.innerError;
        this.userMessage = details.userMessage || details.message;
        this.suggestion = details.suggestion;
        this.timestamp = Date.now();
        
        // 保持原始堆栈跟踪
        if (details.innerError && details.innerError.stack) {
            this.stack = `${this.stack}\nCaused by: ${details.innerError.stack}`;
        }
        
        // 设置堆栈跟踪到上下文
        if (details.context) {
            details.context.stackTrace = this.stack;
        }
    }

    /**
     * 转换为JSON格式
     */
    toJSON(): object {
        return {
            name: this.name,
            code: this.code,
            message: this.message,
            userMessage: this.userMessage,
            level: this.level,
            category: this.category,
            context: this.context,
            suggestion: this.suggestion,
            timestamp: this.timestamp,
            stack: this.stack
        };
    }

    /**
     * 转换为用户友好的格式
     */
    toUserFormat(): {
        code: string;
        message: string;
        suggestion?: string;
    } {
        return {
            code: this.code,
            message: this.userMessage,
            suggestion: this.suggestion
        };
    }

    /**
     * 静态工厂方法 - 创建系统错误
     */
    static system(message: string, context?: ErrorContext): GameError {
        return new GameError({
            code: ERROR_CODES.SYSTEM_SERVICE_UNAVAILABLE,
            message,
            level: ErrorLevel.ERROR,
            category: ErrorCategory.SYSTEM,
            context,
            userMessage: '系统暂时不可用，请稍后重试'
        });
    }

    /**
     * 静态工厂方法 - 创建业务错误
     */
    static business(code: ErrorCode, message: string, userMessage?: string, context?: ErrorContext): GameError {
        return new GameError({
            code,
            message,
            level: ErrorLevel.ERROR,
            category: ErrorCategory.BUSINESS,
            context,
            userMessage: userMessage || message
        });
    }

    /**
     * 静态工厂方法 - 创建验证错误
     */
    static validation(message: string, context?: ErrorContext): GameError {
        return new GameError({
            code: ERROR_CODES.VALIDATION_PARAMETER_INVALID,
            message,
            level: ErrorLevel.WARN,
            category: ErrorCategory.VALIDATION,
            context,
            userMessage: '输入参数有误，请检查后重试'
        });
    }

    /**
     * 静态工厂方法 - 创建权限错误
     */
    static authorization(message: string, context?: ErrorContext): GameError {
        return new GameError({
            code: ERROR_CODES.AUTH_PERMISSION_DENIED,
            message,
            level: ErrorLevel.WARN,
            category: ErrorCategory.AUTHORIZATION,
            context,
            userMessage: '权限不足，无法执行此操作'
        });
    }

    /**
     * 静态工厂方法 - 从普通错误转换
     */
    static fromError(error: Error, code?: ErrorCode, context?: ErrorContext): GameError {
        return new GameError({
            code: code || ERROR_CODES.SYSTEM_SERVICE_UNAVAILABLE,
            message: error.message,
            level: ErrorLevel.ERROR,
            category: ErrorCategory.SYSTEM,
            context,
            innerError: error,
            userMessage: '系统发生错误，请稍后重试'
        });
    }
}

/**
 * 错误工厂类 - 提供便捷的错误创建方法
 */
export class ErrorFactory {
    /**
     * 创建物品不存在错误
     */
    static itemNotFound(itemId: string, context?: ErrorContext): GameError {
        return GameError.business(
            ERROR_CODES.BUSINESS_ITEM_NOT_FOUND,
            `Item not found: ${itemId}`,
            '物品不存在',
            { ...context, metadata: { itemId } }
        );
    }

    /**
     * 创建余额不足错误
     */
    static insufficientBalance(required: number, current: number, context?: ErrorContext): GameError {
        return GameError.business(
            ERROR_CODES.BUSINESS_INSUFFICIENT_BALANCE,
            `Insufficient balance: required ${required}, current ${current}`,
            '余额不足',
            { ...context, metadata: { required, current } }
        );
    }

    /**
     * 创建参数验证错误
     */
    static invalidParameter(paramName: string, value: any, context?: ErrorContext): GameError {
        return GameError.validation(
            `Invalid parameter: ${paramName} = ${value}`,
            { ...context, metadata: { paramName, value } }
        );
    }

    /**
     * 创建用户未找到错误
     */
    static userNotFound(userId: string, context?: ErrorContext): GameError {
        return GameError.authorization(
            `User not found: ${userId}`,
            { ...context, metadata: { userId } }
        );
    }

    /**
     * 创建服务不可用错误
     */
    static serviceUnavailable(serviceName: string, context?: ErrorContext): GameError {
        return GameError.system(
            `Service unavailable: ${serviceName}`,
            { ...context, serviceName, metadata: { serviceName } }
        );
    }
}
